Ext.namespace("Ext.un");

//下拉框Store
Ext.un.typeStore = new Ext.data.ArrayStore({
	fields:[
		{name:'value'},
 		{name:'label'}
	],
	data:[
		[1,'官网'],
		[2,'专题'],
		[3,'注册'],
		[4,'启动游戏']
	]
});
//grid 多选框
Ext.un.virtualRelationSM = Ext.un.virtualRelationSM = new Ext.grid.CheckboxSelectionModel({
	onRefresh : function(){
        var ds = this.grid.store,index,
            s = this.getSelections();
        for(var i=0,len = s.length; i < len; i++){
            var r = s[i];
            if((index = ds.indexOfId(r.id)) != -1){
            	this.grid.getView().onRowSelect(index);
            }
        }
        if(s.length != this.selections.getCount()){
            this.fireEvent('selectionchange', this);
        }
    },
    selectRow : function(index, keepExisting, preventViewNotify){
        var recordSel = this.grid.store.getAt(index);
        if(recordSel){
	        this.superclass().selectRow.call(this,index, keepExisting, preventViewNotify);
        }
    },deselectRow : function(index, preventViewNotify){
        this.superclass().deselectRow.call(this,index, preventViewNotify);
        var record = this.grid.store.getAt(index);
        var val = record.data.id;
    },
    clearSelections : function(fast){
		 this.superclass().clearSelections.call(this,false);
		 this.cleanAll();
	},
	cleanAll : function(){
		if(this.isLocked()){
			return
		}
		this.grid.getView().removeRows();
	}
});
//grid 内容
Ext.un.virtualRelationCm =  new Ext.grid.ColumnModel([
	Ext.un.virtualRelationSM,
	{header:'操作Id',dataIndex:'optId',width:24},
	{header:'类型id',dataIndex:'typeId',width:24},
	{header:'类型名称',dataIndex:'typeName',width:34},
	{header:'Url缺省',dataIndex:'defaultUrl',width:30},
	{header:'详情缺省',dataIndex:'defaultGame',width:30},
	{header:'按钮缺省',dataIndex:'btnGame',width:30},
	{header:'url',dataIndex:'url',width:120}
	
]);
//grid 内容
Ext.un.virtualRelationStore = new Ext.un.ArrayStoreExt({
    fields:[
    	{name : 'optId',mapping : 'optId',type : 'int'},
    	{name : 'typeId',mapping : 'typeId',type : 'int'},
		{name : 'typeName',mapping : 'typeName',type : 'string'},
		{name : 'url',mapping : 'url',type : 'string'},
		{name : 'defaultUrl',mapping : 'defaultUrl',type : 'string'},
		{name : 'defaultGame',mapping : 'defaultGame',type : 'string'},
		{header:'btnGame',dataIndex:'btnGame',width:30}
    ]
});
//formpanel
Ext.un.virtualRelationForm = function(refs){
 return new Ext.FormPanel({
	autoHeight:true,
	labelWidth:60,
	frame:true,
	items:[{
			xtype: 'panel',
	        layout: 'column',
	        defaults:{
	        	anchor:'90%'
	        },
	        items: [
	            {
	                xtype: 'panel',
	                layout: 'form',
	                columnWidth: 0.4,
	                items: [
	                    {
	                        xtype: 'textfield',
	                        fieldLabel: 'Url',
	                        name:'url',
	                        vtype:'url'
	                    },{
                    		xtype:'checkbox',
                    		columnWidth: 0.5,
                			fieldLabel:'url缺省',
                			name:'defaultUrl'
	                	}
	                ]
	            },
	            {
					xtype:'panel',
					layout:'form',
					columnWidth:0.3,
					items:[{
						xtype: 'combo',
						anchor:'90%',
				        fieldLabel: '类型种类',
				        hiddenName:'typeId',
				        triggerAction : 'all',
				        valueField : 'value',
						displayField : 'label',
						emptyText : '选择类型种类',
				        store:Ext.un.typeStore,
				        mode:'local',
				        allowBlank : false,
				        editable:false,
						blankText : '选择类型种类',
						listeners:{
							"select":function(){
								Ext.getCmp("typeName").setValue(this.lastSelectionText);
							}
						}
					},{
            			xtype:'checkbox',
            			fieldLabel:'详情缺省',
            			name:'defaultGame'
	                },{
						xtype:'hidden',
						name:'typeName',
						id:'typeName'
					},{
						xtype:'hidden',
						name:'optId',
						id:'optId',
						value:'-9'
					}]
				},
	            {
	                xtype: 'panel',
	                columnWidth: 0.2,
	                layout:'form',
	                items: [
	                    {
	                    	xtype:'panel',
	                    	layout:'column',
	                    	items:[
	                    		{
	                    			xtype: 'button',
			                        text: '保存',
			                        columnWidth: 0.3,
			                        handler:function(){
			                        	//refs.onQuery();
			                        	if(refs.triggerForm.getForm().isValid()){
				                        	var values = refs.triggerForm.getForm().getValues(false);
				                        	var record = new Ext.data.Record(values,values['typeId']);
				                        	var removed = refs.store.indexOfId(values['typeId']);
				                        	if(removed>-1){
				                        		refs.store.removeAt(removed);
				                        	}
				                        	refs.store.loadRecords({records:[record]},{add:true},true);
			                        	}
			                        }
	                    		},{
			                        xtype: 'button',
			                        columnWidth: 0.3,
			                        text: '确定',
			                        handler:function(){
			                        	var urlFlag = 0;
			                        	var gameFlag = 0;
			                        	var btnFlag = 0;
			                        	var records = refs.triggerGrid.selModel.getSelections();
			                        	var optId = "";
			                        	var typeId = "";
			                        	var typeName = "";
			                        	var url = "";
			                        	var status = "";
			                        	for(var i=0,len = records.length;i<len;i++){
			                        		if(typeId != ""){
			                        			typeId+= refs.mergeChar;
			                        			typeName+=refs.mergeChar;
			                        			url+=refs.mergeChar;
			                        			optId+=refs.mergeChar;
			                        			status+=refs.mergeChar;
			                        		}
				                        	typeId += records[i].get('typeId');
				                        	typeName += records[i].get('typeName');
				                        	url += records[i].get('url');
				                        	optId += records[i].get('optId');
				                        	var urlSt = records[i].get('defaultUrl') == "on"?1:0;
				                        	if(urlSt==1){
				                        		urlFlag++;
				                        	}
											if(urlFlag > 1){
				                        		Ext.Msg.alert("提示","缺省Url只能选一个");
				                        		return;
				                        	}
				                        	var gameSt = records[i].get('defaultGame') == "on"?2:0;
				                        	if(gameSt==2){
				                        		gameFlag++;
				                        	}
				                        	if(gameFlag > 1){
				                        		Ext.Msg.alert("提示","缺省详情只能选一个");
				                        		return;
				                        	}
				                        	var btnSt = records[i].get('btnGame') == "on"? 4:0;
				                        	if(btnSt==4){
				                        		btnFlag++;
				                        	}
				                        	if(btnFlag > 1){
				                        		Ext.Msg.alert("提示","缺省按钮只能选一个");
				                        		return;
				                        	}
				                        	status += (urlSt + gameSt + btnSt);
			                        	}
			                        	if(urlFlag == 0){
			                        		Ext.Msg.alert("提示","缺省Url必须选择一个");
				                        	return;
			                        	}
			                        	if(refs.bindfield){
			                        		Ext.getCmp(refs.bindfield).setValue(typeId);
			                        	}
			                        	if(refs.bindUrl){
			                        		Ext.getCmp(refs.bindUrl).setValue(url);
			                        	}
			                        	if(refs.bindOptId){
			                        		Ext.getCmp(refs.bindOptId).setValue(optId);
			                        	}
			                        	if(refs.bindDefault){
			                        		Ext.getCmp(refs.bindDefault).setValue(status);
			                        	}
			                        	refs.setValue(typeName);
			                        	refs.hideWin();
			                        }
			                    },{
				            		xtype:'button',
				            		columnWidth: 0.4,
				            		text:'重置',
				            		handler:function(){
				            			refs.onReset();
				            		}
				            	}
	                    	]
	                        
	                    },{
	                    	xtype:'checkbox',
	            			columnWidth: 0.5,
	            			fieldLabel:'按钮缺省',
	            			name:'btnGame'
	                    }
	                ]
	            }
	        ]
		}]
});
}
// combox Trigger
Ext.un.virtualRelationTrigger = function(config){
	config || (config = {});
	if(!config.store){
		config.store = Ext.un.virtualRelationStore;
	}
	if(!config.cm){
		config.cm = Ext.un.virtualRelationCm;
	}
	if(!config.triggerForm){
		config.triggerForm = Ext.un.virtualRelationForm(this);
	}
	if(!config.sm){
		config.sm = Ext.un.virtualRelationSM;
	}
	Ext.un.virtualRelationTrigger.superclass.constructor.apply(this,arguments);
}

Ext.extend(Ext.un.virtualRelationTrigger,Ext.un.TriggerTemplet,{
	mergeChar:",",
	noSelected:[],
	initComponent: function() {
		Ext.un.virtualRelationTrigger.superclass.initComponent.call(this);
        this.triggerGrid.store.on("load",function(){
			var records = [];
			for(var i=0;i<this.noSelected.length;i++){
				var record = this.noSelected[i];
				var relRec = this.getRecord(record.data.id, record.data.name);
				if(relRec){
					records[records.length]=relRec;
					this.noSelected.splice(i,1);
					i--;
				}
			}
			this.doSelectedRow(records);
		},this);
	},
	onTriggerClick:function(){
		// Trigger Event
		this.showContainer.show(this.el);
		this.doClearRecords();
		this.triggerGrid.selModel.clearSelections();
		this.onloadData();
	},
	delArrayIndex:function(array,index){
		if(array.length >= index){
			for(var i=index;i<array.length;i++){
				var j= (i===array.length)?i:++i;
				array[i]=array[j];
				array[array.length-1]=null;
			}
		}
	},
	onloadData:function(){
		// init grid store
		var typeId = "",typeName="",url="",optId="";
		if(this.bindfield){
			typeId = Ext.getCmp(this.bindfield).getValue();
			typeName = this.getValue();
			url = Ext.getCmp(this.bindUrl).getValue();
			optId = Ext.getCmp(this.bindOptId).getValue();
		}
		if(!typeId || !typeName || !url){
			return;
		}
		var records = [];
		var idSplit = typeId.split(this.mergeChar);
		var nameSplit = typeName.split(this.mergeChar);
		var urlSplit = url.split(this.mergeChar);
		var optIdSplit = optId.split(this.mergeChar);
		if(idSplit.length == 0 || nameSplit.length != idSplit.length || nameSplit.length != urlSplit.length){
			return;
		}
		for(var i=0,len = idSplit.length;i<len;i++){
			var values = {};
			values['typeId']=idSplit[i];
			values['typeName']=nameSplit[i];
			values['url']=urlSplit[i];
			values['optId']=optIdSplit[i];
			var record = this.getRecord(idSplit[i],urlSplit[i]);//new Ext.data.Record(values, idSplit[i]);
			if(record == null){
				this.loadRecord(this.createRecord(values));
				continue;
			}
			records[i]=record;
		}
		this.doSelectedRow(records);
	},
	doClearRecords:function(){
		this.triggerGrid.selModel.selections.clear();
		this.triggerGrid.store.removeAll();
		this.triggerForm.getForm().reset();
	},
	doSelectedRow:function(records){
		if(records.length > 0){
			this.triggerGrid.selModel.selectRecords(records,true);
		}
	},
	createRecord:function(values){
		return new Ext.data.Record(values,values['typeId']);
	},
	loadRecord:function(record){
		this.triggerGrid.store.loadRecords({records:[record]},{add:true},true);
	},
	getRecord:function(typeId,typeName){
		var record = this.triggerGrid.store.getById(typeId);
		if(record && record.data.url == typeName){
			return record;
		}
		return null;
	},
    onCellClick:function(trigger){
    	
    }
});
